import { FC, ReactNode, useCallback } from 'react';
import { Tooltip, Space } from 'antd';
import classNames from 'classnames';
import _ from 'lodash';
import { useNavigate } from 'react-router-dom';
import { observer } from 'mobx-react';

import Button from '@components/Button';
import Icons from '@components/Icons';

import './index.less';

export type HeaderProps = {
  /** 标题 */
  title?: ReactNode;

  /** 返回地址 */
  backPath?: string;

  /**
   * 返回提示
   * @default '返回'
   */
  backTooltip?: string;

  /** 返回后触发事件 */
  onBack?: () => void;

  children?: ReactNode;

  /** 类名 */
  className?: string;
};

const Header: FC<HeaderProps> = ({
  title,
  backPath,
  backTooltip = '返回',
  onBack,
  children,
  className
}) => {
  const navigate = useNavigate();

  // 返回
  const onBackBtnClick = useCallback(() => {
    if (backPath && _.isString(backPath)) {
      navigate(backPath);
      if (onBack && _.isFunction(onBack)) {
        onBack();
      }
    } else {
      window.history.back();
    }
  }, [backPath, navigate, onBack]);

  return (
    <div className={classNames('rb-page-header-div-wapper', className)}>
      {backPath && (
        <div className="rb-page-header-backpath-div-wapper">
          <Tooltip title={backTooltip} placement="bottom" getTooltipContainer={that => that}>
            <Button
              shape="circle"
              type="text"
              icon={<Icons type="ArrowLeftOutlined" onClick={() => onBackBtnClick()} />}
            />
          </Tooltip>
        </div>
      )}
      {title && <div className="rb-page-header-title-div-wapper">{title}</div>}
      <div className="rb-page-header-children-div-wapper">
        <Space>{children}</Space>
      </div>
    </div>
  );
};

export default observer(Header);
